package com.itheima.stock.sharding;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;
import java.util.Optional;
import java.util.stream.Collectors;

public class CommonAlg4tb implements PreciseShardingAlgorithm<Date>, RangeShardingAlgorithm<Date> {
    /**
     * 精确查
     *个股----年月
     *
     * @param tbNames       数据库别名
     * @param shardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> tbNames, PreciseShardingValue<Date> shardingValue) {
        //获取逻辑表名称  t_order
        String logicTableName = shardingValue.getLogicTableName();
        //获取分片键名称
        String columnName = shardingValue.getColumnName();
        //获取sql语句条件值
        Date curDatetime = shardingValue.getValue();
        String yearMonth = new DateTime(curDatetime).toString("yyyyMM");
        Optional<String> result = tbNames.stream().filter((tbName) -> tbName.endsWith(yearMonth)).findFirst();
        if (result.isPresent()) {
            return result.get();
        }

        return null;
    }

    /**
     * 范围查
     *
     * @param tbNames
     * @param shardingValue
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> tbNames, RangeShardingValue<Date> shardingValue) {
        //获取sql条件-范围值
        Range<Date> valueRange = shardingValue.getValueRange();
        if (valueRange.hasLowerBound()) {
            //获取起始值
            Date startDate = valueRange.lowerEndpoint();
            int startYearMonth = Integer.valueOf(new DateTime(startDate).toString("yyyyMM"));
            tbNames = tbNames.stream().filter((tbName) -> Integer.parseInt(tbName.substring(tbName.lastIndexOf("_") + 1)) >= startYearMonth).collect(Collectors.toList());

        }
        if (valueRange.hasUpperBound()) {
            //获取上限
            //获取起始值
            Date endDate = valueRange.lowerEndpoint();
            int endYearMonth = Integer.valueOf(new DateTime(endDate).toString("yyyyMM"));
            tbNames = tbNames.stream().filter((tbName) -> Integer.parseInt(tbName.substring(tbName.lastIndexOf("_") + 1)) <= endYearMonth).collect(Collectors.toList());

        }
        return tbNames;
    }
}
